﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SharedGenomics.Core;
using SharedGenomics.Workbench.PresentationModel;

namespace SharedGenomics.Workbench.Views.WindowsForms
{
    public class DataGrid<T> : IDataGrid<T>
    {
        public DataGrid(DataGridView gridView)
        {
            gridView.ThrowIfNull("gridView");
            this.GridView = gridView;

            BindingSource bs = gridView.DataSource as BindingSource;
            bs.ThrowIfNull<ArgumentException>("Grid view must have a binding source data source");
            this.BindingSource = bs;
        }

        public IEnumerable<DataGridColumnInfo> Columns
        {
            set
            {
                this.GridView.Columns.Clear();

                foreach (DataGridColumnInfo col in value ?? Enumerable.Empty<DataGridColumnInfo>())
                {
                    DataGridViewColumn gridViewColumn = new DataGridViewTextBoxColumn()
                    {
                        HeaderText = col.HeaderText,
                        DataPropertyName = col.PropertyName,
                        ValueType = col.DataType
                    };

                    if (col.Format != null)
                    {
                        gridViewColumn.DefaultCellStyle.Format = col.Format;
                    }

                    this.GridView.Columns.Add(gridViewColumn);
                }
            }
        }

        public object Data
        {
            set
            {
                this.BindingSource.DataSource = value;
            }
        }

        private DataGridView GridView { get; set; }
        private BindingSource BindingSource { get; set; }
    }
}
